package com.jourwon.spring.boot.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息转换器配置
 *
 * @author JourWon
 * @date 2022/6/3
 */
@Configuration
public class MessageConvertersConfig {

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                // 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
                SerializerFeature.WriteDateUseDateFormat,
                // 将为null的字符串显示为""
                SerializerFeature.WriteNullStringAsEmpty,
                // List字段如果为null,输出为[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                // 是否输出值为null的字段,默认为false,如下配置则输出值为null的map字段
                SerializerFeature.WriteMapNullValue
                );

        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
        // 表示序列化的时候将直接返回原来的键值而不做任何处理
        // NameFilter nameFilter = (object, name, value) -> name;
        // serializeConfig.addFilter(UiConfiguration.class, nameFilter);
        // serializeConfig.addFilter(SwaggerResource.class, nameFilter);
        // 首字母大写
        // serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.PascalCase);
        // 因为js中的数字类型不能包含所有的java long值,所以在序列换成json时,将所有的long变成string
        serializeConfig.put(Long.class , ToStringSerializer.instance);
        serializeConfig.put(Long.TYPE , ToStringSerializer.instance);
        fastJsonConfig.setSerializeConfig(serializeConfig);

        fastJsonConfig.setCharset(StandardCharsets.UTF_8);

        converter.setFastJsonConfig(fastJsonConfig);

        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(supportedMediaTypes);

        return converter;
    }

}
